//
//  CQRefreshTableViewController.m
//  HiChat
//
//  Created by wqiong on 16/1/12.
//  Copyright © 2016年 wqiong. All rights reserved.
//

#import "CQRefreshTableViewController.h"
#import "MJRefresh.h"
#import "CQMessageCell.h"
#import "CQFootTableView.h"
#import "CQAddView.h"
#import "EMChatManagerDefs.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>
#import "CQContactAddView.h"

#define userTo @"test1"


//@constant eMessageBodyType_Text 文本类型
//@constant eMessageBodyType_Image 图片类型
//@constant eMessageBodyType_Video 视频类型
//@constant eMessageBodyType_Location 位置类型
//@constant eMessageBodyType_Voice 语音类型
//@constant eMessageBodyType_File 文件类型
//@constant eMessageBodyType_Command 命令类型
//*/
//typedef NS_ENUM(NSInteger, MessageBodyType) {
//    eMessageBodyType_Text = 1,
//    eMessageBodyType_Image,
//    eMessageBodyType_Video,
//    eMessageBodyType_Location,
//    eMessageBodyType_Voice,
//    eMessageBodyType_File,
//    eMessageBodyType_Command
//};


@interface CQRefreshTableViewController () <CQFootViewDelegate, UITableViewDelegate, UITableViewDataSource, EMChatManagerDelegate, ChangeViewHeightDelegate, PhotoDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, AVAudioPlayerDelegate, CQAddViewDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) CQFootTableView *footV;
@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) CQAddView *addView;
@property (nonatomic, retain) NSMutableArray *imageArr;
@property (nonatomic, retain) UIImageView *imageRecord;
@property (nonatomic, strong)NSURL *tmpFile;
//录音
@property (nonatomic, strong)AVAudioRecorder *recorder;
//播放
@property (nonatomic, strong)AVAudioPlayer *player;

//录音状态(是否录音)
@property (nonatomic, assign)BOOL isRecoding;

@property (nonatomic, assign) NSInteger durtion;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) CQMessageCell *voiceCell;
@end

@implementation CQRefreshTableViewController

- (void)dealloc
{
    [_voiceCell release];
    [_timer release];
    [_recorder release];
    [_player release];
    [_tmpFile release];
    [_addView release];
    [_arr release];
    [_UserTo release];
    [_footV release];
    [_tableV release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.UserTo;
    self.arr = [NSMutableArray array];
     [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    self.view.backgroundColor = [UIColor magentaColor];
    
    /*1,conversationForChatter:获取或创建与8001的会话
      2,isGroup:会话类型*/
    
//    EMConversation *conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:@"test1" conversationType:eConversationTypeChat];
    //获取内存中所有会话
//    NSArray *conversations = [[EaseMob sharedInstance].chatManager conversations];
    //获取DB中的所有会话
  //  NSArray *conversations = [[EaseMob sharedInstance].chatManager loadAllConversationsFromDatabaseWithAppend2Chat:YES];
    
    [self creatTabview];
    [self creatOther];
    [self createRecord];
    
}

- (void)createRecord {
    
    self.tmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@"TmpFile"]];
    
    //设置后台播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    //判断后台有没有播放
    if (session == nil) {
        
        NSLog(@"Error creating sessing:%@", [sessionError description]);
        
    } else {
        
        [session setActive:YES error:nil];
        
    }
 
}

- (void)creatOther {
    self.addView = [[CQAddView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100)];
    self.addView.delegate = self;
    [self.view addSubview:self.addView];
}

- (void)creatTabview
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
   // [self.tableV addGestureRecognizer:tapGR];
    [self.view addSubview:self.tableV];
    [_tableV release];
    [self creatFootTableView];
    
    self.imageArr = [NSMutableArray array];
    
    for (NSInteger i = 1; i < 21; i++) {
        
        // 拼接图片的名字
        // 注意!!!仔细查看图片的序号是1还是01/001...
        // 若序号是01的形式, 用%02ld的形式,
        NSString *fileName = [NSString stringWithFormat:@"VoiceSearchFeedback%03ld@2x.png", i];
        // 创建UIImage类型对象
        UIImage *image = [UIImage imageNamed:fileName];
        // 将图片添加到数组
        [self.imageArr addObject:image];
    }
    self.imageRecord = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"VoiceSearchFeedback001@2x.png"]];
    self.imageRecord.frame = CGRectMake(100, 100, 100, 100);
    self.imageRecord.animationImages = self.imageArr;
    [self.view addSubview:self.imageRecord];
    [self.imageRecord setHidden:YES];
    [_imageRecord release];

}

- (void)tapAction {
    [self.footV.textField resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        self.footV.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.bounds.size.width, 50);
        self.addView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.voiceCell = [tableView cellForRowAtIndexPath:indexPath];
    EMMessage *message = [self.arr objectAtIndex:indexPath.row];
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    switch (msgBody.messageBodyType) {
        case eMessageBodyType_Voice:
            [self playVoiceAction:msgBody tableView:tableView];
            break;
            
        default:
            break;
    }
    
    [self.footV.textField resignFirstResponder];
}

- (void)playVoiceAction:(id<IEMMessageBody>)msgBody tableView:(UITableView *)tableView{
    [_player stop];
    self.voiceCell.contentLabel.textColor = [UIColor redColor];
    EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
    NSError *playError;
    if (body.localPath.length != 0) {
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:body.localPath] error:&playError];
    } else {
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:body.remotePath] error:&playError];
    }
    if (self.player == nil) {
        NSLog(@"Error crenting player: %@", [playError description]);
    } else {
        [_player play];
    }
    self.player.delegate = self;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    EMMessage *message = [self.arr objectAtIndex:indexPath.row];
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    
    switch (msgBody.messageBodyType) {
        case eMessageBodyType_Text:
            return [[CQMessageCell class] hightWithStr:[message.messageBodies.firstObject text]] + 40;
            break;
            
        case eMessageBodyType_Image:
            return 200;
            break;
            
        case eMessageBodyType_Voice:
            return 80;
            break;
            
        default:
            return 0;
            break;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EMMessage *message = [self.arr objectAtIndex:indexPath.row];
    static NSString *CellIdentifier = @"Cell";
    // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //改为以下的方法
    CQMessageCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
    if (cell == nil) {
        cell = [[CQMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
   // CQMessageCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.message = message;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


//CQFootTableView代理方法,按send发送信息
- (void)sendMessage:(NSString *)text
{
    if (text.length != 0) {
        self.addView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
        EMChatText *txtChat = [[EMChatText alloc] initWithText:text];
        EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:txtChat];
        
        // 生成message
        EMMessage *message = [[EMMessage alloc] initWithReceiver:self.UserTo bodies:@[body]];
        message.messageType = eMessageTypeChat; // 设置为单聊消息
        //message.messageType = eConversationTypeGroupChat;// 设置为群聊消息
        //message.messageType = eConversationTypeChatRoom;// 设置为聊天室消息
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
        [self.arr addObject:message];
        [self.tableV reloadData];
        self.tableV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 45);
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
        if (indexPath.row < [self.tableV numberOfRowsInSection:0]) {
            [self.tableV scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }

    }
}


- (void)recoverkeyBoard {
    [self.footV.textField resignFirstResponder];
}

- (void)creatFootTableView
{
    self.footV = [[CQFootTableView alloc] init];
    self.footV.delegate = self;
    self.footV.fieldDelegate = self;
    self.footV.frame = CGRectMake(0, self.view.bounds.size.height - 165, self.view.bounds.size.width, 55);
    
    [self.view addSubview:self.footV];
}

- (void)photoDelegate{
    UIImagePickerController *imagePC = [[UIImagePickerController alloc] init];
    
    imagePC.delegate = self;
    imagePC.allowsEditing = YES;
    imagePC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:imagePC animated:YES completion:nil];
    // [self.navigationController pushViewController:imagePC animated:YES];
    [imagePC release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSLog(@"%@", [info objectForKey:@"UIImagePickerControllerOriginalImage"]);
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [self sendmessageImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)sendmessageImage:(UIImage *)image {
    
    EMChatImage *imgChat = [[EMChatImage alloc] initWithUIImage:image displayName:@"displayName"];
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithChatObject:imgChat];
    
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.UserTo bodies:@[body]];
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
    [self.arr addObject:message];
    [self.tableV reloadData];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
    if (indexPath.row < [self.tableV numberOfRowsInSection:0]) {
        [self.tableV scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}


- (void)addDelegate:(UIButton *)sender {
    if (sender.selected != YES) {
        [UIView animateWithDuration:0.2 animations:^{
            self.tableV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 150);
            self.footV.frame = CGRectMake(0, self.view.frame.size.height - 150, self.view.frame.size.width, 50);
            self.addView.frame = CGRectMake(0, self.view.frame.size.height - 100, self.view.frame.size.width, 100);
        }];
        sender.selected = YES;

    } else {
        [UIView animateWithDuration:0.2 animations:^{
            self.tableV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 45);
            self.footV.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.bounds.size.width, 50);
            self.addView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
        }];
        sender.selected = NO;
    }
}
- (void)ChangeViewHeight:(NSInteger)height {
    self.footV.frame = CGRectMake(0, self.view.frame.size.height - height, self.view.bounds.size.width, 50);
    self.tableV.frame = CGRectMake(0, -210, self.view.frame.size.width, self.view.frame.size.height);
    
}

- (void)voiceDelegate:(UIButton *)sender {
    
    if (sender.selected) {
        [self.imageRecord setHidden:NO];
        [self.imageRecord startAnimating];
        [self startRecord];
    } else {
        [self.imageRecord setHidden:YES];
        [self.imageRecord stopAnimating];
        [self stopRecord:sender];
    }
}

- (void)startRecord {
    [_player stop];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [_timer fireDate];
    self.durtion = 0;
    //开始录音,将所获取到得录音存到文件里
    self.recorder = [[AVAudioRecorder alloc] initWithURL:_tmpFile settings:nil error:nil];
    
    //准备记录录音
    [_recorder prepareToRecord];
    
    //启动或者恢复记录的录音文件
    [_recorder record];
    
    _player = nil;
}

- (void)updateTimer:(NSTimer *)sender{
    NSLog(@"%ld", self.durtion++);　　　　//1,2,3,4,5秒计时
}

- (void)stopRecord:(UIButton *)sender {
    //停止录音
    [self.timer invalidate];
    [_recorder stop];
    _recorder = nil;
    
    NSError *playError;
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:_tmpFile error:&playError];
    //当播放录音为空, 打印错误信息
    if (self.player == nil) {
        NSLog(@"Error crenting player: %@", [playError description]);
    } else {
        if (sender.state == UIControlEventTouchDown) {
            [self sendMessageVoiceFile:_tmpFile];
        }
    }
    
    self.player.delegate = self;
}

- (void)sendMessageVoiceFile:(NSURL *)file {
    NSString *fileName = [NSString stringWithFormat:@"%@", file];
    fileName = [fileName substringFromIndex:8];
    
    EMChatVoice *voiceChat = [[EMChatVoice alloc] initWithFile:fileName displayName:@"displayName"];
    EMVoiceMessageBody *body = [[EMVoiceMessageBody alloc] initWithChatObject:voiceChat];
    body.duration = self.durtion;
    NSLog(@"dsadsadas%ld", body.duration);
    // 生成message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.UserTo bodies:@[body]];
    message.messageType = eMessageTypeChat; // 设置为单聊消息
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil];
    [self.arr addObject:message];
    [self.tableV reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
    if (indexPath.row < [self.tableV numberOfRowsInSection:0]) {
        [self.tableV scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}

- (void)returnViewHeight:(NSInteger)height {
    self.tableV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 45);
    self.footV.frame = CGRectMake(0, self.view.frame.size.height - 50, self.view.bounds.size.width, 50);
    self.addView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 100);
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"dsadsadsa");
    self.voiceCell.contentLabel.textColor = [UIColor whiteColor];
}

// 收到消息的回调
-(void)didReceiveMessage:(EMMessage *)message
{
    NSLog(@"受到消息多撒啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
    [self.arr addObject:message];
    [self.tableV reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.arr.count - 1 inSection:0];
    if (indexPath.row < [self.tableV numberOfRowsInSection:0]) {
        [self.tableV scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    id<IEMMessageBody> msgBody = message.messageBodies.firstObject;
    switch (msgBody.messageBodyType) {
        case eMessageBodyType_Text:
        {
            // 收到的文字消息
            NSString *txt = ((EMTextMessageBody *)msgBody).text;
            NSLog(@"收到的文字是 txt -- %@",txt);
        }
            break;
        case eMessageBodyType_Image:
        {
            // 得到一个图片消息body
            EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
            NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
            NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"大图的secret -- %@"    ,body.secretKey);
            NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
            NSLog(@"大图的下载状态 -- %lu",body.attachmentDownloadStatus);
            
            
            // 缩略图sdk会自动下载
            NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
            NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
            NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
            NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
            NSLog(@"小图的下载状态 -- %lu",body.thumbnailDownloadStatus);
        }
            break;
        case eMessageBodyType_Location:
        {
            EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
            NSLog(@"纬度-- %f",body.latitude);
            NSLog(@"经度-- %f",body.longitude);
            NSLog(@"地址-- %@",body.address);
        }
            break;
        case eMessageBodyType_Voice:
        {
            // 音频sdk会自动下载
            EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
            NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
            NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在（音频会自动调用）
            NSLog(@"音频的secret -- %@"        ,body.secretKey);
            NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"音频文件的下载状态 -- %lu"   ,body.attachmentDownloadStatus);
            NSLog(@"音频的时间长度 -- %lu"      ,body.duration);
        }
            break;
        case eMessageBodyType_Video:
        {
            EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;
            
            NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
            NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"视频的secret -- %@"        ,body.secretKey);
            NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"视频文件的下载状态 -- %lu"   ,body.attachmentDownloadStatus);
            NSLog(@"视频的时间长度 -- %lu"      ,body.duration);
            NSLog(@"视频的W -- %f ,视频的H -- %f", body.size.width, body.size.height);
            
            // 缩略图sdk会自动下载
            NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
            NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailRemotePath);
            NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
            NSLog(@"缩略图的下载状态 -- %lu"      ,body.thumbnailDownloadStatus);
        }
            break;
        case eMessageBodyType_File:
        {
            EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
            NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
            NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
            NSLog(@"文件的secret -- %@"        ,body.secretKey);
            NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
            NSLog(@"文件文件的下载状态 -- %lu"   ,body.attachmentDownloadStatus);
        }
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
